<template>
  <div v-loading="localGridLoading">
    <transition name="slide-fade">
    <div v-if="needHead && needBar && writeAble && headVisible">
      <bpm-c-subtitle :title="title"
                      :isCollapse="false" />
        <bpm-d-splitgrid class="content"
                         :validateExp="validateExp"
                         :gridStatus="gridStatus"
                       v-model="selectedGridInfo"
                       v-if="head === 'split'" />
        <bpm-d-postgrid class="content"
                        :validateExp="validateExp"
                        :gridStatus="gridStatus"
                       v-model="selectedGridInfo"
                       v-else-if="head === 'post'"/>
        <bpm-d-paymentgridtraingrid class="content"
                                    :validateExp="validateExp"
                                    ref="paymentgridtraingrid"
                                    :gridStatus="gridStatus"
                                  v-model="selectedGridInfo"
                                  v-else-if="head === 'train'" />
        <bpm-d-paymentgridtaxigrid class="content"
                                   :validateExp="validateExp"
                                   :gridStatus="gridStatus"
                                 v-model="selectedGridInfo"
                                 v-else-if="head === 'taxi'" />
        <bpm-d-paymentgridhotelgrid class="content"
                                    :validateExp="validateExp"
                                    :gridStatus="gridStatus"
                                    ref="paymentgridhotelgrid"
                                  v-model="selectedGridInfo"
                                  v-else-if="head === 'hotel'" />
        <bpm-d-paymentgridextragrid class="content"
                                    :validateExp="validateExp"
                                    :gridStatus="gridStatus"
                                    ref="paymentgridextragrid"
                                  v-model="selectedGridInfo"
                                  v-else-if="head === 'extra'" />
        <bpm-d-paymentgrid class="content"
                           :gridStatus="gridStatus"
                           ref="paymentgrid"
                           @paymentgridSaveClicked="paymentgridSaveClicked"
                           :validateExp="validateExp"
                           v-else-if="head === 'payment'" />
    </div>
    </transition>
    <bpm-c-gridbar v-if="needBar && writeAble" :note="note"
                   :showArray="navButton"
                   :show="headVisible"
                   :checkedList="checkedList"
                   :gridStatus="gridStatus"
                   @makeCertClicked="makeCertClicked"
                   @addClicked="addClicked"
                   @cancelClicked="cancelClicked"
                   @saveClicked="saveClicked"
                   @updateClicked="updateClicked"
                   @deleteClicked="deleteClicked"/>
    <bpm-c-gridmain
      @gridClick="gridClicked"
      @gridDBLClicked="gridDBLClicked"
      :gridStatus="gridStatus"
      v-model="checkedList"
      :warnList="warnList"
      :height="height"
      :head="head"
      :showCheckbox="showCheckbox && writeAble"
      :gridInfo="gridInfo"
      :gridTitleInfo="gridTitleInfo"
      :gridShowInfo="gridShowInfo"
      :gridEditInfo="gridEditInfo"
      :gridTypeInfo="gridTypeInfo"
      :gridWidthInfo="gridWidthInfo"
      @cellDoubleSelect="cellDoubleSelect"
      @gridCellEditEnd="gridCellEditEnd"
    />
    <bpm-c-gridpage
      :pageMax="pageMax"
      :pageStart="pageStart"
      :pageCount="pageCount"
      @gridPageChanged="gridPageChanged"/>
  </div>
</template>

<script>
import { mapState, mapActions } from 'vuex'
export default {
  name: 'bpmDGrid',
  model: {
    prop: 'editItem',
    event: 'editItemChanged'
  },
  props: {
    writeAble: {
      type: Boolean,
      default: true
    },
    head: {
      type: String,
      default: 'normal'
    },
    note: {
      type: String,
      default: ''
    },
    showArray: {
      type: Array,
      default () {
        return ['makeCert', 'add', 'delete']
      }
    },
    needHead: {
      type: Boolean,
      default: true
    },
    needBar: {
      type: Boolean,
      default: true
    },
    gridInfo: {
      type: Array,
      default () {
        return []
      }
    },
    showCheckbox: {
      type: Boolean,
      default: false
    },
    height: {
      type: Number,
      default: 200
    },
    gridTitleInfo: {
      type: Array,
      default () {
        return []
      }
    },
    gridShowInfo: {
      type: Array,
      default () {
        return []
      }
    },
    gridEditInfo: {
      type: Array,
      default () {
        return []
      }
    },
    gridWidthInfo: {
      type: Array,
      default () {
        return []
      }
    },
    gridTypeInfo: {
      type: Array,
      default () {
        return []
      }
    },
    editItem: {
      type: Object,
      default () {
        return {}
      }
    },
    pageMax: {
      type: Number,
      default: 0
    },
    pageStart: {
      type: Number,
      default: 0
    },
    pageCount: {
      type: Number,
      default: 10
    },
    warnList: {
      type: Array,
      default () {
        // return [1] 第二行warn
        return []
      }
    },
    validateExp: {
      type: Object,
      default () {
        return {}
      }
    },
    showExtraStyle: {
      type: Boolean,
      default: false
    }
  },
  data () {
    return {
      tabIndex: 0,
      radioValue: 'IN',
      dialogVisible: false,
      selectedGridInfo: {},
      budgetSubject: '',
      checkedList: [],
      gridStatus: 'normal'
    }
  },
  computed: {
    ...mapState(['pageType', 'pageTypeEnum', 'lang', 'otherI18n', 'dialogLoading']),
    localGridLoading () {
      return this.dialogloading > 0
    },
    navButton () {
      if (this.gridStatus === 'normal') {
        return this.showArray
      } else if (this.gridStatus === 'add') {
        return ['save', 'hide', 'delsel']
      } if (this.gridStatus === 'update') {
        return ['save', 'hide', 'delsel']
      } if (this.gridStatus === 'readonly') {
        return ['hide']
      }
    },
    title () {
      if (this.gridStatus === 'normal') {
        return this.otherI18n.gridTitleNormal
      } else if (this.gridStatus === 'add') {
        return this.otherI18n.gridTitleAdd
      } if (this.gridStatus === 'update') {
        return this.otherI18n.gridTitleModify
      } if (this.gridStatus === 'readonly') {
        return this.otherI18n.gridTitleReadonly
      }
    },
    headVisible () {
      if (this.gridStatus === 'normal') {
        return false
      } else if (this.gridStatus === 'add') {
        return true
      } if (this.gridStatus === 'update') {
        return true
      } if (this.gridStatus === 'readonly') {
        return true
      }
    }
  },
  watch: {
    checkedList (v) {
      console.log('check changed:::::::', v, v.length)
      this.$emit('gridCheckedChanged', v)
    },
    gridInfo (to) {
      this.checkedList = []
      this.selectedGridInfo = {}
    },
    gridStatus (to, from) {
      if (to === 'normal' && from !== 'normal') {
        this.checkedList = []
        this.selectedGridInfo = {}
      }
    }
  },
  methods: {
    ...mapActions(['resetGridSelectRowWhBtReimburseDdSub', 'resetGridSelectRowWhBtFareDetails', 'resetGridSelectRowWhBtStayDetails']),
    ...mapActions(['resetGridSelectRowWhBtTravelSubsidyDetails', 'resetGridSelectRowWhBtTransportationDetails', 'resetGridSelectRowWhBtReimburseCostShare', 'resetGridSelectRowWhBtReimburseRcmDetail']),
    hideGridHead (isSave) {
      // 提示场景：仅新增后保存成功进行疑问
      if (isSave && this.gridStatus === 'add') {
        // this.$confirm(
        //   this.otherI18n.keeponAdd,
        //   this.getResource('alert.header.inf'),
        //   {
        //     confirmButtonText: this.otherI18n.sureBig,
        //     cancelButtonText: this.otherI18n.cancelBig,
        //     showClose: false
        //   }
        // ).then(() => {
        //   // do nothing
        // }).catch(() => {
        //   this.hideAction()
        // })
        if (this.head === 'payment') {
          this.resetGridSelectRowWhBtReimburseDdSub({me: this})
        }
        if (this.head === 'train') {
          this.resetGridSelectRowWhBtFareDetails({me: this})
        }
        if (this.head === 'hotel') {
          this.resetGridSelectRowWhBtStayDetails({me: this})
        }
        if (this.head === 'extra') {
          this.resetGridSelectRowWhBtTravelSubsidyDetails({me: this})
        }
        if (this.head === 'split') {
          this.resetGridSelectRowWhBtReimburseCostShare({me: this})
        }
        if (this.head === 'post') {
          this.resetGridSelectRowWhBtReimburseRcmDetail({me: this})
        }
      } else {
        this.hideAction()
      }
    },
    hideAction () {
      this.gridStatus = 'normal'
      this.selectedGridInfo = {}
      if (this.head === 'payment') {
        this.resetGridSelectRowWhBtReimburseDdSub({me: this})
        return
      }
      if (this.head === 'train') {
        this.resetGridSelectRowWhBtFareDetails({me: this})
        return
      }
      if (this.head === 'hotel') {
        this.resetGridSelectRowWhBtStayDetails({me: this})
        return
      }
      if (this.head === 'extra') {
        this.resetGridSelectRowWhBtTravelSubsidyDetails({me: this})
        return
      }
      if (this.head === 'split') {
        this.resetGridSelectRowWhBtReimburseCostShare({me: this})
        return
      }
      if (this.head === 'post') {
        this.resetGridSelectRowWhBtReimburseRcmDetail({me: this})
      }
    },
    pcontent (i) {
      if (!this.selectedGridInfo || !this.gridShowInfo) {
        return ''
      }
      return this.selectedGridInfo[this.gridShowInfo[i]]
    },
    selectedGridInfoChanged (selectedGridInfo, cellIndex) {
      this.$emit('selectedGridInfoChanged', selectedGridInfo, cellIndex)
    },
    updateClicked () {
      if (!this.writeAble) { return }
      console.log('update clicked.')
      if (this.checkedList && this.checkedList.length === 1) {
        this.gridStatus = 'update'
        this.$emit('gridStatusChanged', this.gridStatus)
        console.log(this.selectedGridInfo)
        this.$emit('updateClicked', this.selectedGridInfo)
      } else {
        // alert.qxzhjl
        this.$message({
          type: 'warning',
          message: this.getLanguage('label.whBtReimburse.reimbStandardMoney')
        })
      }
    },
    addClicked () {
      if (!this.writeAble) { return }
      if (this.head === 'post' && this.pageType === this.pageTypeEnum.approveFee) {
        if (this.isMakeCert() === '-1') {
          this.alert(this.getResource('alert.yzzbyxtj')) // 已经制证,不允许添加
          return
        }
        let mid = this.$store.state.fyftCheckedMids
        if (mid === null || mid === '') {
          this.alert(this.getResource('alert.chooseDetails')) // 请选择一条费用分摊明细
          return
        }
        if (mid.split(',').length > 1) {
          this.alert(this.getResource('alert.chooseDetails')) // 只能选择一条费用分摊明细
          return
        }
      }
      if (this.head === 'payment' && this.pageType === this.pageTypeEnum.draft) {
        let companyCode = this.$store.state.ssc.reimburse.whBtReimburse.reimbursecompanycode
        if (companyCode === null || companyCode === '' || typeof companyCode === 'undefined') {
          this.alert(this.getResource('alert.information.qxxzgs'))
          return
        }
        let costcenterCode = this.$store.state.ssc.reimburse.whBtReimburse.reimbursecostcentercode
        if (costcenterCode === null || costcenterCode === '' || typeof costcenterCode === 'undefined') {
          this.alert(this.getResource('alert.information.qxzcbzx'))
          return
        }
      }
      // console.log('aaaa===', this.head)
      if (this.head === 'extra' && this.pageType === this.pageTypeEnum.approveFee) {
        if (this.isMakeCert() === '-1') {
          this.alert(this.getResource('alert.yzzbyxtj')) // 已经制证,不允许添加
          return
        }
      }
      // 清空选择
      this.checkedList = []
      this.selectedGridInfo = {}
      this.gridStatus = 'add'
      this.$emit('gridStatusChanged', this.gridStatus)
      this.$emit('addClicked')
    },
    deleteClicked () {
      if (!this.writeAble) { return }
      if (!this.checkedList || !this.selectedGridInfo || this.checkedList.length <= 0) {
        return
      }
      if (this.checkedList.length === 1) {
        let index = this.checkedList[0]
        console.log(index)
      }
      this.$emit('deleteClicked', this.selectedGridInfo)
    },
    cancelClicked () {
      if (!this.writeAble) { return }
      this.gridStatus = 'normal'
      this.$emit('gridStatusChanged', this.gridStatus)
      this.hideGridHead(false)
    },
    saveClicked () {
      if (!this.writeAble) { return }
      // mmsuna before save, validate IT.
      if (this.head === 'train') {
        let jsonResult = this.$refs.paymentgridtraingrid.checkValidate()
        if (!jsonResult.result) {
          this.alert(this.otherI18n.pleaseInput + jsonResult.title)
          return
        }
      }
      if (this.head === 'hotel') {
        let jsonResult = this.$refs.paymentgridhotelgrid.checkValidate()
        if (!jsonResult.result) {
          this.alert(this.otherI18n.pleaseInput + jsonResult.title)
          return
        }
      }
      if (this.head === 'extra') {
        let jsonResult = this.$refs.paymentgridextragrid.checkValidate()
        if (!jsonResult.result) {
          this.alert(this.otherI18n.pleaseInput + jsonResult.title)
          return
        }
      }
      if (this.head === 'payment') {
        let jsonResult = this.$refs.paymentgrid.checkValidate()
        if (!jsonResult.result) {
          this.alert(this.otherI18n.pleaseInput + jsonResult.title)
          return
        }
      }
      // 清空选择
      this.checkedList = []
      this.$emit('saveClicked', this.selectedGridInfo)
    },
    paymentgridSaveClicked (v) {
      // 保存
      if (v === 'save') {
        this.hideGridHead(false)
        // 关闭
      } else if (v === 'close') {
        this.hideGridHead(false)
      }
    },
    gridClicked (index) {
      console.log('clicked', index)
      if (!this.writeAble) { return }
      if (this.gridStatus === 'normal') {
        // this.gridStatus = 'update'
        this.checkedList = [index]
        if (this.head !== 'payment') {
          this.selectedGridInfo = Object.assign({}, this.gridInfo[index])
        }
      }
      /* this.headVisible = !this.headVisible */
      this.$emit('updateClicked', this.selectedGridInfo)
      this.$emit('gridClicked', index, this.selectedGridInfo)
    },
    gridDBLClicked (index) {
      console.log('double clicked', index)
      if (!this.writeAble) { return }
      if (this.pageType === this.pageTypeEnum.approveFee) {
        if (this.isMakeCert() === '-1') {
          this.alert(this.getResource('alert.information.yjzzbyxxg')) // 已经制证不允许修改
          return
        }
      }
      if (this.pageType !== this.pageTypeEnum.draft && this.showExtraStyle &&
        (this.gridInfo[index].subjectcode === '500307000901' || this.gridInfo[index].subjectcode === '500307000101')) {
        return
      }
      if (this.gridStatus !== 'normal') {
        this.hideGridHead(false)
      }
      setTimeout(() => {
        this.gridStatus = 'update'
        this.$emit('gridStatusChanged', this.gridStatus)
        this.checkedList = [index]
        this.selectedGridInfo = Object.assign({}, this.gridInfo[index])
        console.log(this.selectedGridInfo)
        this.$emit('updateClicked', this.selectedGridInfo)
        this.$emit('gridDBLClicked', index, this.selectedGridInfo)
      }, 100)
    },
    setDialogClose () {
      this.gridStatus = 'normal'
      this.$emit('gridStatusChanged', this.gridStatus)
    },
    makeCertClicked () {
      if (!this.writeAble) { return }
      this.$emit('makeCertClicked')
    },
    gridPageChanged (v) {
      if (!v || !v.name) { return }
      // 清空选择和恢复状态
      this.checkedList = []
      this.gridStatus = 'normal'
      this.selectedGridInfo = {}
      this.$emit('gridStatusChanged', this.gridStatus)
      console.log('gridPageChanged', v)
      this.$emit('gridPageChanged', v)
    },
    gridCellEditEnd: function (record, recordFieldValue) {
      this.$emit('gridCellEditEnd', record, recordFieldValue)
    },
    cellDoubleSelect () {
      setTimeout(() => {
        this.cancelClicked()
      }, 100)
    }
  }
}
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
  .head {
    width: 100%;
    text-align: left;
    background-color: #16F6F6;
    height: 24px;
  }

  .content {
    width: 100%;
    display: block;
  }

  .icon {
    font-size: 12px;
    padding-left: 12px;
    color: #ab51ab;
    line-height: 24px;
    height: 20px;
    margin: 0;
    margin-left: 30px;
    float: left;
    width: 300px;
    font-weight: 100;
  }
  .slide-fade-enter-active {
    transition: all .5s ease;
  }
  .slide-fade-leave-active {
    transition: all .5s cubic-bezier(1.0, 0.5, 0.8, 1.0);
  }
  .slide-fade-enter, .slide-fade-leave-to
    /* .slide-fade-leave-active for below version 2.1.8 */ {
    transform: translateY(-10px);
    opacity: 0;
  }
</style>
